/**
 * **************** Copyright (C) *****************
 * <p/>
 * Version       Date            Author
 * ─────────────────────────────────────
 * V1.0        2017/7/14         yellowlgx
 * <p/>
 * **************** End of Head *******************
 */
package com.skyworth.ui.blurbg;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.skyworth.commen.ui.R;
import com.skyworth.util.FastBlur;


/**
 * @author : yellowlgx
 * @ClassName BlurringView
 * @Description : TODO
 * @date : 2017/7/14 16:13
 */
public class NewBlurringView extends View
{
    private int mBlurRadius;
    private int mDownsampleFactor;
    private int mOverlayColor;

    private View mBlurredView;
    private int mBlurredViewWidth, mBlurredViewHeight;

    private boolean mDownsampleFactorChanged;
    private Bitmap mBitmapToBlur, mBlurredBitmap;
    private Canvas mBlurringCanvas;

    private boolean needAnim = true;

    private ValueAnimator showAnim, outAnim;

    private boolean needBlur = true;

    public NewBlurringView(Context context)
    {
        this(context, null);
    }

    public NewBlurringView(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        final Resources res = getResources();
        final int defaultBlurRadius = res.getInteger(R.integer.default_blur_radius);
        final int defaultDownsampleFactor = res.getInteger(R.integer.default_downsample_factor);
        final int defaultOverlayColor = res.getColor(R.color.default_overlay_color);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PxBlurringView);
        setBlurRadius(a.getInt(R.styleable.PxBlurringView_blurRadius, defaultBlurRadius));
        setDownsampleFactor(a.getInt(R.styleable.PxBlurringView_downsampleFactor,
                defaultDownsampleFactor));
        setOverlayColor(a.getColor(R.styleable.PxBlurringView_overlayColor, defaultOverlayColor));
        a.recycle();
    }

    public void setNeedAnim(boolean needAnim)
    {
        this.needAnim = needAnim;
    }

    private void startBlur()
    {
        this.setVisibility(View.VISIBLE);
        if (needAnim)
        {
            if (showAnim == null)
            {
                showAnim = ObjectAnimator.ofFloat(this, "alpha", 0, 1);
                showAnim.setInterpolator(new AccelerateDecelerateInterpolator());
                showAnim.setDuration(400);
                showAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
                {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation)
                    {
                        if (NewBlurringView.this.getVisibility() != View.VISIBLE)
                            NewBlurringView.this.setVisibility(View.VISIBLE);
                    }
                });
            }
            if (outAnim != null)
                outAnim.cancel();
            showAnim.start();
        } else
        {
            if (this.getAlpha() != 1)
                this.setAlpha(1);
        }
    }

    public void dismissBlur(boolean needDelay, long delayTiem)
    {
        if (needAnim)
        {
            if (outAnim == null)
            {
                outAnim = ObjectAnimator.ofFloat(this, "alpha", 1, 0);
                outAnim.setInterpolator(new AccelerateDecelerateInterpolator());
                outAnim.setDuration(300);
                if (needDelay)
                {
                    outAnim.setStartDelay(delayTiem);
                }
                outAnim.addListener(new AnimatorListenerAdapter()
                {
                    @Override
                    public void onAnimationEnd(Animator animation)
                    {
                        super.onAnimationEnd(animation);
                        NewBlurringView.this.setVisibility(View.GONE);
                    }
                });
            }
            if (showAnim != null)
                showAnim.cancel();
            outAnim.start();
        } else
        {
            this.setVisibility(View.GONE);
        }
    }

    public void setBlurredView(View blurredView)
    {
        mBlurredView = blurredView;
        invalidate();
        startBlur();
    }

    public void setNeedBlur(boolean needBlur)
    {
        this.needBlur = needBlur;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        if (mBlurredView != null && needBlur)
        {
            if (prepare())
            {
                // If the background of the blurred view is a color drawable, we use it to clear
                // the blurring canvas, which ensures that edges of the child views are blurred
                // as well; otherwise we clear the blurring canvas with a transparent color.
                if (mBlurredView.getBackground() != null && mBlurredView.getBackground() instanceof
                        ColorDrawable)
                {
                    mBitmapToBlur.eraseColor(((ColorDrawable) mBlurredView.getBackground()).getColor());
                } else
                {
                    mBitmapToBlur.eraseColor(Color.TRANSPARENT);
                }

                mBlurredView.draw(mBlurringCanvas);
                blur();

                canvas.save();
                canvas.translate(mBlurredView.getX() - getX(), mBlurredView.getY() - getY());
                canvas.scale(mDownsampleFactor, mDownsampleFactor);
                canvas.drawBitmap(mBlurredBitmap, 0, 0, null);
                canvas.restore();
            }
            canvas.drawColor(mOverlayColor);
        }
    }

    public void setBlurRadius(int radius)
    {
        if (mBlurRadius != radius)
            mBlurRadius = radius;
    }

    public void setDownsampleFactor(int factor)
    {
        if (factor <= 0)
        {
            throw new IllegalArgumentException("Downsample factor must be greater than 0.");
        }

        if (mDownsampleFactor != factor)
        {
            mDownsampleFactor = factor;
            mDownsampleFactorChanged = true;
        }
    }

    public void setOverlayColor(int color)
    {
        if (mOverlayColor != color)
        {
            mOverlayColor = color;
        }
    }

    protected boolean prepare()
    {
        final int width = mBlurredView.getWidth();
        final int height = mBlurredView.getHeight();

        if (mBlurringCanvas == null || mDownsampleFactorChanged
                || mBlurredViewWidth != width || mBlurredViewHeight != height)
        {
            mDownsampleFactorChanged = false;

            mBlurredViewWidth = width;
            mBlurredViewHeight = height;

            int scaledWidth = width / mDownsampleFactor;
            int scaledHeight = height / mDownsampleFactor;

            // The following manipulation is to avoid some RenderScript artifacts at the edge.
            if (scaledWidth % 4 > 0)
                scaledWidth = scaledWidth - scaledWidth % 4 + 4;
            if (scaledHeight % 4 > 0)
                scaledHeight = scaledHeight - scaledHeight % 4 + 4;

            if (mBlurredBitmap == null
                    || mBlurredBitmap.getWidth() != scaledWidth
                    || mBlurredBitmap.getHeight() != scaledHeight)
            {
                mBitmapToBlur = Bitmap.createBitmap(scaledWidth, scaledHeight,
                        Bitmap.Config.ARGB_8888);
                if (mBitmapToBlur == null)
                {
                    return false;
                }

                mBlurredBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight,
                        Bitmap.Config.ARGB_8888);
                if (mBlurredBitmap == null)
                {
                    return false;
                }
            }

            mBlurringCanvas = new Canvas(mBitmapToBlur);
            mBlurringCanvas.scale(1f / mDownsampleFactor, 1f / mDownsampleFactor);
        }
        return true;
    }

    protected void blur()
    {
        mBlurredBitmap = FastBlur.doBlur(mBitmapToBlur, mBlurRadius, true);
    }

    private Bitmap getIndeViewBitmap(View view)
    {
        int scaledWidth = view.getWidth() / mDownsampleFactor;
        int scaledHeight = view.getHeight() / mDownsampleFactor;
        Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(bitmap);
        canvas.scale(1f / mDownsampleFactor, 1f / mDownsampleFactor);
        view.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onDetachedFromWindow()
    {
        super.onDetachedFromWindow();
    }
}
